package com.imay.live.fragment.room;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.imay.base.fragment.BaseDialogFragment;
import com.imay.live.R;
import com.imay.live.adapter.MusicAdapter;
import com.imay.live.manager.LocalMusicManager;
import com.imay.live.manager.MusicDownLoadManager;
import com.imay.live.model.MusicModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.RecyclerViewUtil;
import com.imay.live.utils.SimpleMediaPlayerUtil;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.imay.live.model.MusicModel.STATU_DOWNLOADING;
import static com.imay.live.model.MusicModel.STATU_SELECTED;
import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by nick on 2017/7/24.
 * BGM 选择
 */

public class MusicSelectFragment extends BaseDialogFragment implements BaseQuickAdapter.OnItemClickListener, View.OnClickListener ,MusicDownLoadManager.DownloadStatuListener {

    private TwinklingRefreshLayout music_select_trl_refresh;
    private RecyclerView rcv_music_select;
    private TextView tv_complete_music_select;
    private String loadMusicListCommand;
    private List<MusicModel> musicModels;
    private MusicAdapter musicAdapter;
    private SimpleMediaPlayerUtil simpleMediaPlayerUtil;
    private int playingPosition;
    private String selectFilePath,tempFilePath;
    private int selectMusicId;


    public static MusicSelectFragment newInstance() {
//        Bundle args = new Bundle();
        MusicSelectFragment fragment = new MusicSelectFragment();
//        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_music_select;
    }

    @Override
    protected boolean isTranslucentBackground() {
        return true;
    }

    @Override
    protected int getWindowAnimations() {
        return R.style.dialog_from_bottom;
    }

    @Override
    protected boolean isMatchParent() {
        return true;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        musicModels = new ArrayList<>();
        music_select_trl_refresh = $(R.id.music_select_trl_refresh);
        rcv_music_select = $(R.id.rcv_music_select);
        tv_complete_music_select = $(R.id.tv_complete_music_select);
        tv_complete_music_select .setOnClickListener(this);


        RecyclerViewUtil.setLinearLayoutManagerWithoutDivider(getContext(), rcv_music_select);
        music_select_trl_refresh.setBottomView(new LoadingView(getContext()));
        music_select_trl_refresh.setEnableLoadmore(false);
        music_select_trl_refresh.setEnableRefresh(false);
        music_select_trl_refresh.setEnableOverScroll(false);
        loadMusic();
//        music_select_trl_refresh.setOnRefreshListener(new RefreshListenerAdapter() {
//            @Override
//            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
//
//            }
//
//            @Override
//            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
//            }
//        });
        simpleMediaPlayerUtil = SimpleMediaPlayerUtil.getInstance();
        LocalMusicManager.getInstance().getLocalMusicList();
        MusicDownLoadManager.getInstance().setDownloadStatuListener(this);

    }

    private void loadMusic() {
        loadMusicListCommand = ProtoRequestHelper.task(ProtoHttpFactory.getMusicList(0)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                if (loadMusicListCommand.equals(command)) {
                    Result<List<MusicModel>> listResult = JSON.parseObject(data, new TypeReference<Result<List<MusicModel>>>() {
                    }.getType());
                    if (listResult.result == CodeSuccess) {
                        musicModels.addAll(LocalMusicManager.getInstance().checkMusicExist(listResult.data));
                        musicModels.add(0,getEmptyItem());
                        musicAdapter = new MusicAdapter(musicModels);
                        rcv_music_select.setAdapter(musicAdapter);
                        musicAdapter.setOnItemClickListener(MusicSelectFragment.this);
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                if (getActivity()!=null){
                    ErrorResult.toastError(getActivity(),code);
                }

            }
        });
    }




    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        MusicModel model = musicModels.get(position);
        if (model.getMusicId()==-1){
            clearSelect();
            return;
        }
        switch (model.getStatu()){
            case MusicModel.STATU_NO_DOWNLOAD:
                model.setDownLoadId(MusicDownLoadManager.getInstance().createDownLoadRequset(model.getMusicUrl(),model.getMucicName()));
                model.setStatu(STATU_DOWNLOADING);
                tempFilePath = "";
                selectMusicId = 0;

                break;
            case MusicModel.STATU_DOWNLOADED:
                simpleMediaPlayerUtil.stop();
                File file = new File(LocalMusicManager.musicDownLoadPath,model.getMucicName());
                boolean initSucess = simpleMediaPlayerUtil.init(getActivity(),file);
                refreshStatu();
                if (initSucess) {
                    simpleMediaPlayerUtil.play();
                    model.setStatu(STATU_SELECTED);
                    model.setPlaying(true);
                    playingPosition = position;
                    tempFilePath = file.getPath();
                    selectMusicId = model.getMusicId();
                }
                break;
            case MusicModel.STATU_SELECTED:
                if (model.isPlaying()){
                    simpleMediaPlayerUtil.pause();
                    model.setPlaying(false);
                }else{
                    simpleMediaPlayerUtil.play();
                    model.setPlaying(true);
                }
                break;
            case MusicModel.STATU_DOWNLOADING:
                MusicDownLoadManager.getInstance().cancle(model.getDownLoadId());
                model.setStatu(MusicModel.STATU_NO_DOWNLOAD);
                tempFilePath = "";
                selectMusicId = 0;

                break;

        }
        musicAdapter.notifyItemChanged(position);

    }

    private void refreshViewAfterDownload(long id,int statu){
        for (int i = 0; i <musicModels.size() ; i++) {
            MusicModel model = musicModels.get(i);
            if (id == model.getDownLoadId()){
                model.setStatu(statu);
                musicAdapter.notifyItemChanged(i);
                break;
            }
        }
    }
    private void refreshStatu(){
        for (int i = 0; i <musicModels.size() ; i++) {
            MusicModel model = musicModels.get(i);
            if (model.getStatu()==MusicModel.STATU_SELECTED){
                model.setStatu(MusicModel.STATU_DOWNLOADED);
                musicAdapter.notifyItemChanged(i);
                break;
            }
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_complete_music_select:
                selectFilePath = tempFilePath;
                dismiss();
                simpleMediaPlayerUtil.stop();
                break;

        }
    }

    @Override
    public void onStop() {
        clearSelect();
        super.onStop();
    }

    private void clearSelect() {
        simpleMediaPlayerUtil.stop();
        tempFilePath="";
        selectMusicId = 0;
        if (musicModels!=null&&!musicModels.isEmpty()) {
            musicModels.get(playingPosition).setStatu(MusicModel.STATU_DOWNLOADED);
            musicAdapter.notifyItemChanged(playingPosition);
            musicModels.get(0).setStatu(STATU_SELECTED);
            musicAdapter.notifyItemChanged(0);
        }
    }

    public String getSelectFilePath() {
        return selectFilePath;
    }

    /**
     *  获取选中音乐的id , 没有选中返回0
     * @return
     */
    public int getSelectMusicId() {
        return selectMusicId;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        simpleMediaPlayerUtil.stop();
        super.onDismiss(dialog);
    }

    @Override
    public void onDownloadSuccess(long id) {
        refreshViewAfterDownload(id,MusicModel.STATU_DOWNLOADED);
    }

    @Override
    public void onDownloadFail(long id) {
        refreshViewAfterDownload(id,MusicModel.STATU_NO_DOWNLOAD);
    }

    private MusicModel getEmptyItem(){
        MusicModel model = new MusicModel();
        model.setStatu(MusicModel.STATU_DOWNLOADED);
        model.setMusicId(-1);
        model.setName(getString(R.string.music_select_no));
        return model;
    }


}
